package com.nekonomics
package api.route

import api.dto.request.{CancelOrderReq, OrderConfirmViewReq, OrderSubmitReq, ReceivedOrderReq}
import api.dto.response.RspEncoder.*
import domain.service.util.TokenService
import domain.service.{CartService, OrderService, PaymentService}
import domain.validation.RequestValidator
import error.{OrderError, PermissionError}

import zio.*
import zio.http.*
import zio.http.Method.*
import zio.json.*

object OrderRoute {
  val routes = baseApiPath / "order" / Routes(

    POST / "confirm-view" -> handler { (req: Request) =>
      for {
        jwt <- extractJwt(req)
        userId <- ZIO.serviceWithZIO[TokenService](_.verifyToken(jwt))
        body <- extractJsonBody[OrderConfirmViewReq](req)
        items = body.items
        _ <- RequestValidator.checkList("items", items)
        confirmData <- ZIO.serviceWithZIO[OrderService](_.confirmDetail(userId, items.toSet))
        rsp = confirmData.toRsp.toJson
      } yield Response.json(rsp)
      
    },



    POST / "submit" -> handler { (req: Request) =>
      for {
        jwt <- extractJwt(req)
        userId <- ZIO.serviceWithZIO[TokenService](_.verifyToken(jwt))
        body <- extractJsonBody[OrderSubmitReq](req)
        // 检查参数是否合法
        _ <- RequestValidator.checkList("skuIds", body.skuIds)
        skuIds = body.skuIds.toSet
        // 生成订单（包含锁定库存，写入order、order_item表）
        order <- ZIO.serviceWithZIO[OrderService](_.submitOrder(userId, skuIds, body.addressId, body.note))
        // 创建支付宝订单
        _ <- ZIO.serviceWithZIO[PaymentService](_.createPayment(order.id, order.totalPrice, "test"))
        // 删除购物车对应的记录
        _ <- ZIO.serviceWithZIO[CartService](_.removeItems(userId, skuIds))
        rsp = order.id.toRsp.toJson
      } yield Response.json(rsp)
    },


    GET / "list" -> handler { (req: Request) =>
      for {
//        pageNum <- extractParam[Int](req)("pageNum")
//        pageSize <- extractParam[Int](req)("pageSize")
//        _ <- RequestValidator.checkPageReq(pageNum = pageNum, pageSize = pageSize)
        jwt <- extractJwt(req)
        userId <- ZIO.serviceWithZIO[TokenService](_.verifyToken(jwt))
        orderList <- ZIO.serviceWithZIO[OrderService](_.list(userId))
        rsp = orderList.toRsp.toJson
      } yield Response.json(rsp)
    },

    POST / "cancel" -> handler { (req: Request) =>
      for {
        jwt <- extractJwt(req)
        userId <- ZIO.serviceWithZIO[TokenService](_.verifyToken(jwt))
        body <- extractJsonBody[CancelOrderReq](req)
        orderId = body.orderId
        order <- ZIO.serviceWithZIO[OrderService](_.getOrder(orderId)).someOrFail(OrderError.OrderNotFound)
        _ <- ZIO.fail(PermissionError.CancelOrderDenied) when order.userId != userId
        _ <- ZIO.serviceWithZIO[PaymentService](_.closeOrderAndPayment(orderId))
        rsp = "success".toRsp.toJson
      } yield Response.json(rsp)
    },

    POST / "receive" -> handler { (req: Request) =>
      for {
        jwt <- extractJwt(req)
        userId <- ZIO.serviceWithZIO[TokenService](_.verifyToken(jwt))
        body <- extractJsonBody[ReceivedOrderReq](req)
        orderId = body.orderId
        order <- ZIO.serviceWithZIO[OrderService](_.getOrder(orderId)).someOrFail(OrderError.OrderNotFound)
        _ <- ZIO.fail(PermissionError.PermissionDenied) when order.userId != userId
        _ <- ZIO.serviceWithZIO[OrderService](_.receivedOrder(orderId))
        rsp = "success".toRsp.toJson
      } yield Response.json(rsp)
    }



//    GET / "detail" -> handler { (req: Request) =>
//      for {
//        jwt <- extractJwt(req)
//        userId <- ZIO.serviceWithZIO[TokenService](_.verifyToken(jwt))
//        // 按照userId、orderId去查，避免信息穿透到其他用户
//      } yield ???
//      ???
//    }

  )














}
